package com.nmgydy.util;

import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class XmlUtils {

    /** XML转Map */
    public static Map<String, String> toMap(String xml){
        Map<String, String> rest = new HashMap<String, String>();
        SAXReader reader = new SAXReader(false);
        Document doc;
		try {
			doc = reader.read(new ByteArrayInputStream(xml.getBytes("UTF-8")));
			@SuppressWarnings("unchecked")
			List<Element> els = doc.getRootElement().elements();
	        for(Element el : els){
	            rest.put(el.getName().toLowerCase(), el.getTextTrim());
	        }
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
        return rest;
    }
    
    /** Map转XML */
    public static String toXml(Map<String, String> params){
        StringBuilder buf = new StringBuilder();
        buf.append("<xml>");
        for(String key : params.keySet()){
            buf.append("<").append(key).append(">");
            buf.append("<![CDATA[").append(params.get(key)).append("]]>");
            buf.append("</").append(key).append(">\n");
        }
        buf.append("</xml>");
        return buf.toString();
    }
}

